package net.pws.common.jackson;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;

public class JsonDateDeserializer extends JsonDeserializer<Date> {
    
    private static final Log logger = LogFactory.getLog(JsonDateDeserializer.class);
    
    public static final SimpleDateFormat shortFormatter = new SimpleDateFormat("yyyy-MM-dd");
    
    public static final SimpleDateFormat longFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    @Override
    public Date deserialize(JsonParser parser, DeserializationContext context) throws IOException,
                                                                              JsonProcessingException {
        String text = parser.getText();
        if (StringUtils.isEmpty(text)) {
            return null;
        }
        
        try {
            if (text.length() == 10) {
                return shortFormatter.parse(text);
            }
            return longFormatter.parse(text);
        }
        catch (ParseException e) {
            logger.error(e, e);
            return null;
        }
    }
    
}
